package com.zzz.offer.listlastk;


class ListNode {
    int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}


public class ListLastK {

    ListNode[] listNodes;

    public static void main(String[] args) {

    }

    // 我自己最笨的方法  TM 的居然想到 一个数组装。。。真的奇葩啊我
    public ListNode FindKthToTail(ListNode pHead, int k) {
        if (k == 0) {
            return null;
        }
        listNodes = new ListNode[k];
        // write code here
        int count = 0;
        while (pHead != null) {
            listNodes[count % k] = pHead;
            pHead = pHead.next;
            count++;
        }
        if (count >= k) {
            pHead = listNodes[(count) % k];
        } else
            pHead = null;
        return pHead;
    }

    //使用两个空间就完全可以搞定的事情。。。
    // 我自己最笨的方法
    public ListNode FindKthToTail1(ListNode pHead, int k) {
        if (k == 0) {
            return null;
        }

        ListNode lastAccess = pHead;
        ListNode lastKAccess;


        while (k > 0) {
            if (lastAccess == null) {
                return null;
            }
            lastAccess = lastAccess.next;

            k--;
        }

        lastKAccess = pHead;

        while (lastAccess != null) {

            lastKAccess = lastKAccess.next;

            lastAccess = lastAccess.next;
        }
        return lastKAccess;
    }

}
